<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
    <el-form-item label="标题" prop="title">
      <el-input v-model="formData.title" />
    </el-form-item>
    <el-form-item label="副标题" prop="subTitle">
      <el-input v-model="formData.subTitle" />
    </el-form-item>
    <el-form-item label="描述" prop="description">
      <el-input v-model="formData.description" />
    </el-form-item>
    <el-form-item label="图片URL" prop="imageUrl">
      <el-input v-model="formData.imageUrl" />
    </el-form-item>
    <el-form-item label="背景颜色" prop="backgroundColor">
      <el-input v-model="formData.backgroundColor" />
    </el-form-item>
    <el-form-item label="链接URL" prop="linkUrl">
      <el-input v-model="formData.linkUrl" />
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-select v-model="formData.status">
        <el-option label="激活" value="active" />
        <el-option label="未激活" value="inactive" />
      </el-select>
    </el-form-item>
    <el-form-item label="顺序" prop="order">
      <el-input-number v-model="formData.order" />
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, inject } from "vue";
import { ElMessage } from "element-plus";
import { createCarousel, updateCarousel } from "@/api/carousel";
import type { FormInstance } from "element-plus";

const formRef = ref<FormInstance | null>(null);
const dialogType = inject("dialogType", ref<"add" | "edit">("add"));
const formData = inject("formData", ref({
  title: '',
  subTitle: '',
  description: '',
  imageUrl: '',
  backgroundColor: '',
  linkUrl: '',
  status: 'inactive',
  order: 0
}));

const rules = {
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  order: [{ required: true, message: "请输入顺序", trigger: "blur" }]
};

const submit = async () => {
  try {
    await formRef.value?.validate();
    if (dialogType.value === "add") {
      await createCarousel(formData.value);
      ElMessage.success("添加成功");
    } else {
      await updateCarousel(formData.value.id, formData.value);
      ElMessage.success("更新成功");
    }
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

defineExpose({
  submit
});
</script> 